<!--
 * @页面名称:分类管理
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="card catalogManage">
    <div class="catalog-left">
      <div class="fonds-title">三表管理（三合一）</div>
      <el-tree-select
        style="width: 100%"
        check-strictly
        v-model="Fonds_ID"
        @change="onChange"
        node-key="Fonds_ID"
        :props="{ label: 'Fonds_Name', children: 'children' }"
        :data="FondsData"
        :render-after-expand="false"
      />
      <div style="height: calc(100% - 72px)">
        <stable :columns="tableSetting.columns" :data="tableSetting.data" @rowClick="rowClick"></stable>
      </div>
    </div>
    <!-- 中间tree部分数据 -->
    <div class="catalog-center">
      <div class="allBtn">
        <el-button :disabled="leftBtnStatus[0]" type="primary" :icon="Plus" @click="onButtonClick('一级')">一级</el-button>
        <el-button :disabled="leftBtnStatus[1]" type="primary" :icon="Plus" @click="onButtonClick('子级')">子级</el-button>
        <el-button :disabled="leftBtnStatus[2]" :icon="Edit" @click="onButtonClick('编辑')">编辑</el-button>
        <el-button :disabled="leftBtnStatus[3]" type="danger" :icon="Delete" @click="onButtonClick('删除')">删除</el-button>
        <el-button :disabled="leftBtnStatus[4]" :icon="CopyDocument" @click="onButtonClick('复制')">复制</el-button>
        <el-button :disabled="leftBtnStatus[5]" :icon="CirclePlus" @click="onButtonClick('粘贴')">粘贴</el-button>
        <ztree :setting="treeSetting.setting" :nodes="treeSetting.treeData" @onClick="onClick"></ztree>
      </div>
    </div>
    <!-- 右边详细数据显示区域 -->
    <div class="catalog-right">
      <div class="fonds-title">从别的门类导入</div>
      <div style="display: flex">
        <el-select style="flex: 1" v-model="selectChangeFMID">
          <el-option v-for="item in tableSetting.data" :value="item.FM_ID" :label="item.FM_OCName" :key="item.FM_ID">
            {{ item.FM_OCName }}
          </el-option>
        </el-select>
        <el-button style="width: 100px" @click="exportButton" :icon="Upload">导入</el-button>
      </div>
      <div class="detailMsg">
        <el-card title="分类详细信息" shadow="never" style="width: 100%; text-align: center">
          <p>
            <span>分类名称: {{ treeSetting.treeNode.Catalog_Name }}</span>
          </p>
          <p>
            <span>分类代码: {{ treeSetting.treeNode.Catalog_Code }}</span>
          </p>
          <p>
            <span>顺序号: {{ treeSetting.treeNode.Catalog_Order }}</span>
          </p>
          <p><span>是否降序: </span> <a-checkbox :checked="treeSetting.treeNode.Catalog_Enable_DescOrderBy" disabled /></p>
          <p><span>是否展开: </span> <a-checkbox :checked="treeSetting.treeNode.Catalog_Enable_Expand" disabled /></p>
          <p><span>是否启用: </span> <a-checkbox :checked="treeSetting.treeNode.Catalog_Enable" disabled /></p>
          <p>
            <span>备注: {{ treeSetting.treeNode.Catalog_Remark }}</span>
          </p>
        </el-card>
      </div>
    </div>
    <!-- 新增编辑弹框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="50%" draggable>
      <el-form label-width="120px" :model="formData" :rules="rules" ref="formRef">
        <el-row>
          <el-col :span="11">
            <el-form-item label="顺序号:" prop="Catalog_Order">
              <el-input v-model="formData.Catalog_Order"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="默认保管期限:" prop="Catalog_BGQX">
              <!-- <el-input v-model="formData.Catalog_BGQX"></el-input> -->
              <el-select v-model="formData.Catalog_BGQX">
                <el-option v-for="item in BGQXData" :key="item.DDL_ID" :label="item.DDL_Name" :value="item.DDL_ID" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="分类代码:" prop="Catalog_Code">
              <el-input v-model="formData.Catalog_Code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="分类名称:" prop="Catalog_Name">
              <el-input v-model="formData.Catalog_Name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="分类代码2:" prop="Catalog_Code2">
              <el-input v-model="formData.Catalog_Code2"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="分类名称2:" prop="Catalog_Name2">
              <el-input v-model="formData.Catalog_Name2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="分类代码3:" prop="Catalog_Code3">
              <el-input v-model="formData.Catalog_Code3"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="分类名称3:" prop="Catalog_Name3">
              <el-input v-model="formData.Catalog_Name3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="级别:" prop="Catalog_Code3">
              <el-input type="number" v-model="formData.Catalog_Code3"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="父级分类:" prop="Catalog_Name3">
              <el-input v-model="formData.Catalog_Name3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="分类备注:" prop="Catalog_Remark">
              <el-input v-model="formData.Catalog_Remark" :rows="2" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="是否降序:" prop="Catalog_IsDesc">
              <el-checkbox v-model="formData.Catalog_IsDesc" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否启用:" prop="Catalog_Enable">
              <el-checkbox v-model="formData.Catalog_Enable" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否展开:" prop="IsExpanded">
              <el-checkbox v-model="formData.IsExpanded" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否归档范围:" prop="Is_FilingScope">
              <el-checkbox v-model="formData.Is_FilingScope" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否无分类:" prop="Is_UnCatalog">
              <el-checkbox v-model="formData.Is_UnCatalog" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from "vue";
import { Plus, Edit, Delete, CopyDocument, CirclePlus, Upload } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { transTree } from "@/utils/util";
import { getCatalog, getTreeData, getBGQXData, convertToExportData } from "./events";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { pick } from "lodash-es";

const fieldList = ref([
  "Catalog_ID",
  "Catalog_Father",
  "FM_ID",
  "Catalog_Order",
  "Catalog_Code",
  "Catalog_Name",
  "Catalog_Code2",
  "Catalog_Name2",
  "Catalog_Code3",
  "Catalog_Name3",
  "Catalog_Remark",
  "Catalog_Enable_DescOrderBy",
  "Catalog_Enable_Expand",
  "Catalog_Defalut_BGQX",
  "Catalog_Enable"
]);
const { proxy } = useCurrentInstance();
// 全宗数据
const FondsData = ref<any[]>([]);
const Fonds_ID = ref("");
// 复制保存数据
const copyFinalData = ref();
// 粘贴数据暂存
const pasteData = ref<any[]>([]);
// 导入选项数据
const exportSelectData = ref<any[]>([]);
// 保管期限
const BGQXData = ref<any[]>([]);
// 保存当前导入选择项FM_ID
const selectChangeFMID = ref("");
// 表格配置
const tableSetting = reactive({
  columns: [
    { title: "门类归档方式", field: "FM_OCName", sortable: true },
    { title: "备注", field: "FM_Remark", sortable: true }
  ],
  data: [] as any[]
});
// 点击表格保存对象
const clickObj = ref();
// 按钮状态
const leftBtnStatus = ref([true, true, true, true, true, true]);
// tree配置
const treeSetting = reactive({
  setting: {
    // ztree配置
    data: {
      simpleData: {
        enable: true,
        idKey: "Catalog_ID",
        pIdKey: "Catalog_Father"
      },
      key: {
        name: "name"
      }
    },
    view: {
      showIcon: false
    }
  },
  treeData: [] as any[],
  treeNode: {} as any
});
// 弹出框配置
const dialogSetting = reactive({
  visible: false,
  title: ""
});
// 表单绑定字段
const formData = ref<any>({
  Catalog_Code: "",
  Catalog_Name: "",
  Catalog_Code2: "",
  Catalog_Name2: "",
  Catalog_Code3: "",
  Catalog_Name3: "",
  Catalog_Order: 1,
  Catalog_BGQX: "",
  Catalog_Remark: "",
  Catalog_IsDesc: false,
  IsExpanded: true,
  Catalog_Enable: true,
  Is_FilingScope: true,
  Is_UnCatalog: false
});
// 表单规则
const rules = reactive<FormRules>({
  Catalog_Code: [{ required: true, message: "请填写分类代码!", trigger: "blur" }],
  Catalog_Name: [{ required: true, message: "请填写分类名称!", trigger: "blur" }]
});
// 表单实例
const formRef = ref<FormInstance>();
// 获取全宗数据
const getFonds = () => {
  proxy.$vueAxios.get("MasterBaseFonds/GetFondsTree").then((res: any) => {
    FondsData.value = transTree(res.List, "Fonds_ID", "Fonds_Father");
  });
};
// 获取归档数据
const onChange = (value: string) => {
  getCatalog(value).then((res: any) => {
    tableSetting.data = res;
    treeSetting.treeNode = {};
  });
};
// 获取保管期限数据
const getBGQX = () => {
  getBGQXData().then((data: any) => {
    BGQXData.value = data;
  });
};
// 表格单击
const rowClick = ({ row }: any) => {
  clickObj.value = row;
  getTree();
  if (copyFinalData.value) {
    leftBtnStatus.value = [false, true, true, true, true, false];
  } else {
    leftBtnStatus.value = [false, true, true, true, true, true];
  }
};
// 获取树数据
const getTree = () => {
  getTreeData(clickObj.value.FM_ID).then((res: any) => {
    treeSetting.treeData = res;
  });
};
// 点击树节点
const onClick = (treeNode: any) => {
  treeSetting.treeNode = treeNode;
  if (copyFinalData.value) {
    leftBtnStatus.value = [false, false, false, false, false, false];
  } else {
    leftBtnStatus.value = [false, false, false, false, false, true];
  }
};
// 按钮点击事件
const onButtonClick = async (name: string) => {
  switch (name) {
    case "一级":
      dialogSetting.title = "一级新增";
      dialogSetting.visible = true;
      formRef.value?.resetFields();
      nextTick(() => {
        if (treeSetting.treeData.length > 0) {
          const order = treeSetting.treeData[treeSetting.treeData.length - 1].Catalog_Order + 1;
          formData.value.Catalog_Order = order;
        }
      });
      break;
    case "子级":
      dialogSetting.title = "子级新增";
      dialogSetting.visible = true;
      formRef.value?.resetFields();
      nextTick(() => {
        const filterData = treeSetting.treeData.filter((item: any) => {
          return item.Catalog_Father === treeSetting.treeNode.Catalog_ID;
        });
        if (filterData.length > 0) {
          formData.value.Catalog_Order = filterData[filterData.length - 1].Catalog_Order + 1;
        } else {
          formData.value.Catalog_Order = 1;
        }
      });
      break;
    case "编辑":
      formRef.value?.resetFields();
      dialogSetting.title = "三表（三合一）编辑";
      dialogSetting.visible = true;
      nextTick(() => {
        formData.value.Catalog_BGQX = treeSetting.treeNode.Catalog_Defalut_BGQX;
        formData.value.Catalog_Code = treeSetting.treeNode.Catalog_Code;
        formData.value.Catalog_Code2 = treeSetting.treeNode.Catalog_Code2;
        formData.value.Catalog_Code3 = treeSetting.treeNode.Catalog_Code3;
        formData.value.Catalog_Enable = treeSetting.treeNode.Catalog_Enable;
        formData.value.Catalog_IsDesc = treeSetting.treeNode.Catalog_Enable_DescOrderBy;
        formData.value.Catalog_Name = treeSetting.treeNode.Catalog_Name;
        formData.value.Catalog_Name2 = treeSetting.treeNode.Catalog_Name2;
        formData.value.Catalog_Name3 = treeSetting.treeNode.Catalog_Name3;
        formData.value.Catalog_Order = treeSetting.treeNode.Catalog_Order;
        formData.value.Catalog_Remark = treeSetting.treeNode.Catalog_Remark;
        formData.value.IsExpanded = treeSetting.treeNode.Catalog_Enable_Expand;
        formData.value.Is_FilingScope = treeSetting.treeNode.Is_FilingScope;
      });
      break;
    case "删除":
      const allIds = getAllIds(treeSetting.treeNode);
      proxy.$messageBox
        .confirm("确定删除该数据？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          proxy.$vueAxios.post("Master_Base_Catalog/Delete", [...allIds]).then((res: any) => {
            if (res.Mark) {
              proxy.$message.success("删除成功");
              getTree();
            } else {
              proxy.$message.error("删除失败");
            }
          });
        })
        .catch(err => {
          proxy.$message("取消删除");
        });
      break;
    case "复制":
      copyFinalData.value = Object.assign({}, treeSetting.treeNode);
      proxy.$message.success("复制成功!");
      leftBtnStatus.value = [false, false, false, false, false, false];
      break;
    case "粘贴":
      pasteData.value = [];
      proxy.$showLoading({ tip: "正在粘贴数据..." });
      await getPasteData({ ...copyFinalData.value, Catalog_Father: treeSetting.treeNode.Catalog_ID || null }, fieldList.value);
      for (let i = 0; i < pasteData.value.length; i++) {
        await proxy.$vueAxios.post("Master_Base_Catalog", pasteData.value[i], { noLoading: true });
      }
      getTree();
      proxy.$message.success("粘贴成功");
      proxy.$hideLoading();
      break;
  }
};
// 获取所有需要删除的id
const getAllIds = (obj: any) => {
  const ids = [obj.Catalog_ID]; // 当前对象的 Catalog_ID
  if (obj.children && obj.children.length > 0) {
    obj.children.forEach((child: any) => {
      const childIds = getAllIds(child); // 递归获取子级的 Catalog_ID
      ids.push(...childIds);
    });
  }
  return ids;
};
// 处理复制的数据(用作粘贴处理)
const getPasteData = (item: any, fieldList: any[]) => {
  const catalogID = proxy.$global.createID();
  const childrenNode = pick({ ...item, Catalog_ID: catalogID, FM_ID: clickObj.value.FM_ID }, fieldList);
  pasteData.value.push(childrenNode);
  if (item.children && item.children.length) {
    item.children.forEach((subItem: any) => {
      subItem.Catalog_Father = catalogID;
      getPasteData(subItem, fieldList);
    });
  }
};
// 点击导入按钮执行的事件
const exportButton = () => {
  if (selectChangeFMID.value) {
    exportSelectData.value = [];
    getTreeData(selectChangeFMID.value).then((res: any) => {
      const resultTemp = convertToExportData(res, null); // 转换为标准tree数据
      resultTemp.forEach((item: any) => {
        getExportData(item, fieldList.value);
      });
      if (exportSelectData.value.length > 0) {
        proxy.$vueAxios.post("Master_Base_Catalog/AddList", exportSelectData.value).then(() => {
          getTree();
          proxy.$message.success("导入成功");
        });
      }
    });
  }
};
// 处理导入的数据(用作导入数据)
const getExportData = (item: any, fieldList: any[]) => {
  const catalogID = proxy.$global.createID();
  const childrenNode = pick({ ...item, Catalog_ID: catalogID, FM_ID: clickObj.value.FM_ID }, fieldList);
  exportSelectData.value.push(childrenNode);
  if (item.children && item.children.length) {
    item.children.forEach((subItem: any) => {
      subItem.Catalog_Father = catalogID;
      getExportData(subItem, fieldList);
    });
  }
};
// 弹出框确认事件
const handle = () => {
  formRef.value!.validate(isValid => {
    if (isValid) {
      if (dialogSetting.title === "一级新增") {
        proxy.$vueAxios
          .post("Master_Base_Catalog", {
            catalog_ID: proxy.$global.createID(),
            fM_ID: clickObj.value.FM_ID,
            fonds_ID: Fonds_ID.value,
            catalog_Code: formData.value.Catalog_Code,
            catalog_Name: formData.value.Catalog_Name,
            catalog_Enable: formData.value.Catalog_Enable,
            catalog_Enable_Expand: formData.value.IsExpanded,
            catalog_Enable_DescOrderBy: formData.value.Catalog_IsDesc,
            catalog_Defalut_BGQX: formData.value.Catalog_BGQX,
            catalog_Order: formData.value.Catalog_Order,
            catalog_Remark: formData.value.Catalog_Remark,
            is_UnCatalog: formData.value.Is_UnCatalog
          })
          .then(() => {
            dialogSetting.visible = false;
            getTree();
          });
      } else if (dialogSetting.title === "子级新增") {
        proxy.$vueAxios
          .post("Master_Base_Catalog", {
            catalog_ID: proxy.$global.createID(),
            catalog_Father: treeSetting.treeNode.Catalog_ID,
            fM_ID: clickObj.value.FM_ID,
            fonds_ID: Fonds_ID.value,
            catalog_Code: formData.value.Catalog_Code,
            catalog_Name: formData.value.Catalog_Name,
            catalog_Enable: formData.value.Catalog_Enable,
            catalog_Enable_Expand: formData.value.IsExpanded,
            catalog_Enable_DescOrderBy: formData.value.Catalog_IsDesc,
            catalog_Defalut_BGQX: formData.value.Catalog_BGQX,
            catalog_Order: formData.value.Catalog_Order,
            catalog_Remark: formData.value.Catalog_Remark,
            is_UnCatalog: formData.value.Is_UnCatalog
          })
          .then(() => {
            dialogSetting.visible = false;
            getTree();
          });
      } else {
        proxy.$vueAxios
          .put("Master_Base_Catalog", {
            catalog_ID: treeSetting.treeNode.Catalog_ID,
            fM_ID: clickObj.value.FM_ID,
            fonds_ID: Fonds_ID.value,
            catalog_Code: formData.value.Catalog_Code,
            catalog_Name: formData.value.Catalog_Name,
            catalog_Enable: formData.value.Catalog_Enable,
            catalog_Enable_Expand: formData.value.IsExpanded,
            catalog_Enable_DescOrderBy: formData.value.Catalog_IsDesc,
            catalog_Defalut_BGQX: formData.value.Catalog_BGQX,
            catalog_Order: formData.value.Catalog_Order,
            catalog_Remark: formData.value.Catalog_Remark,
            catalog_Father: treeSetting.treeNode.Catalog_Father,
            is_FilingScope: formData.value.Is_FilingScope,
            is_UnCatalog: formData.value.Is_UnCatalog
          })
          .then((res: any) => {
            if (res.Mark) {
              dialogSetting.visible = false;
              getTree();
            }
          });
      }
    }
  });
};

onMounted(() => {
  getFonds();
  getBGQX();
});
</script>

<style scoped lang="scss">
.catalogManage {
  display: flex;
  height: 100%;
  .catalog-left {
    width: 25%;
    .fonds-title {
      height: 40px;
      font-size: 16px;
      line-height: 40px;
      text-align: center;

      // background-color: rgb(245 246 248);
    }
  }
  .catalog-center {
    display: flex;
    flex-direction: column;
    width: 40%;
    height: 100%;
    overflow: auto;
    border-right: 1px solid #d2d2d2;
    .allBtn button {
      margin: 3px 5px;
    }
    .treedata {
      height: 100%;
      padding-left: 20px;
      overflow-y: auto;
    }
  }
  .catalog-right {
    width: 35%;
    .fonds-title {
      height: 40px;
      font-size: 16px;
      line-height: 40px;
      text-align: center;

      // background-color: rgb(245 246 248);
    }
  }
}
</style>
